import './public-path'
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import routes from './routes'
import Vuex from 'vuex'

Vue.use(Vuex)
let setGlobalState = null

const store = new Vuex.Store({
  state: {
    globalState: {},
  },
  mutations: {
    mutateGlobalState(state, value) {
      const { globalState } = state
      state.globalState = { ...globalState, ...value }
    },
  },
  actions: {
    setGlobalState(_, value) {
      setGlobalState && setGlobalState(value)
    },
    setStoreGlobalState({ commit }, value) {
      commit('mutateGlobalState', value)
    },
  },
  modules: {},
})

Vue.config.productionTip = false

let router = null
let instance = null

function render(props = {}) {
  const { container } = props
  router = new VueRouter({
    base: window.__POWERED_BY_QIANKUN__ ? '/app-vue/' : '/',
    mode: 'history',
    routes,
  })

  instance = new Vue({
    router,
    store,
    render: (h) => h(App),
  }).$mount(container ? container.querySelector('#app') : '#app')
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  render()
}

export async function bootstrap() {
  console.log('[vue] vue app bootstraped')
}
export async function mount(props) {
  console.log('[vue] props from main framework', props)
  props.onGlobalStateChange((state, prev) => {
    // state: 变更后的状态; prev 变更前的状态
    console.log('child', state, prev)
    store.dispatch('setStoreGlobalState', state)
  })
  setGlobalState = props.setGlobalState
  store.dispatch('setStoreGlobalState', props.globalState)
  render(props)
}
export async function unmount() {
  instance.$destroy()
  instance.$el.innerHTML = ''
  instance = null
  router = null
}
